require(['../../common'], function() {
  require(['cate.listcates'])
})

define('cate.listcates', [
  'jquery',
  'page/grid'
], function($, Grid) {
  'use strict';

  var sid // site id
  var pid // parent category id


  function createOptions(data) {
    var html = '<option value="0">-- 请选择 --</option>'
    $.each(data, function(key, val) {
      html += '<option value="' + val.id + '">' + val.name + '</option>'
    })
    return html
  }

  /**
   * 获取分类列表
   * @param  {number} sid site id
   * @param  {number} pid parent category id
   * @return {}
   */
  function getCates() {
    // $.get(APP + '?app=cms&m=Cate&a=queryCates', {
    //   sid: sid,
    //   pid: pid
    // })
    //   .done(function(data) {
    //     console.log(data)
    //     // $tbody.html(data)
    //   })
    var url = APP + '?app=cms&m=Cate&a=catelist&sid=' + sid
    location.href = url
  }

  function addCate() {
    var url = APP + '?app=cms&m=Cate&a=addcate&sid=' + sid +
      (pid ? '&pid=' + pid : '')
    location.href = url
  }

  var $sites = $('#sites')
  var $btnAdd = $('#J_add')
  var $sid = $('#sid')
  var sid = $sid.val()


  $.getJSON(APP + '?app=cms&m=Cate&a=siteTreeList')
    .done(function(data) {
      // console.log(data)
      $sites.html(createOptions(data)).val(sid)
    })

  $sites.on('change', function() {
    var val = this.value
    if (val) {
      sid = val
      getCates()
    }
  })

  $btnAdd.on('click', function() {
    if (!sid) {
      alert('请选择站点')
    } else {
      addCate()
    }
  })

  /**
   * [del description]
   * @param  {[type]} ids [description]
   * @return {[type]}     [description]
   */
  function del(ids) {
    var length = 0;

    if (ids) {
      length = 1;
    } else {
      ids = getChecked();
      length = ids[0] == 0 ? ids.length - 1 : ids.length;
      ids = ids.toString();
    }

    if (!len) {
      ui.error('请选择要删除的数据')
      return false
    }

    var sid = "{$sid}";
    if (confirm('{$Think.lang.删除}' + length + '{$Think.lang.条数据}?')) {
      $.post("{:URL('cms/Cate/delCate')}", {
        ids: ids,
        sid: sid
      }, function(res) {
        if (res == '1') {
          ui.success('{$Think.lang.删除成功}');
          removeItem(ids);
        } else {
          ui.error('{$Think.lang.删除失败}');
        }
      });
    }
  }


  var $table = $('.table')
  var $tbody = $table.children('tbody')
  var mygrid = new Grid($table)
  mygrid.init();


  $table.on('click', '.A_del', function() {
    del()
  })

  // 批量删除
  $('#J_del').on('click', function() {

  })

})
